package com.shareppy.normanhttp.tasks.hmac;

import java.util.Calendar;
import java.util.TimeZone;

import org.apache.http.client.methods.HttpPost;

import android.content.Context;

import com.shareppy.normanhttp.AbstractHttpRequest;
import com.shareppy.normanhttp.HttpRequestParams;
import com.shareppy.normanhttp.HttpRequestTask;
import com.shareppy.utils.crypto.CryptoUtil;

public class HMacCredentialRequestTask extends HttpRequestTask {

	private String hmac;
	private String user;

	public HMacCredentialRequestTask(Context context, String service,
			String credential, String hmac) {
		super(context, service);
		this.user = credential;
		this.hmac = hmac;
	}

	@Override
	protected boolean manageCookie() {
		return false;
	}

	@Override
	protected void addCustomHeaders(HttpPost post, HttpRequestParams params) {
		final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
		c.setTimeInMillis(System.currentTimeMillis());
		long currentTime = c.getTime().getTime();
		String authorizationValue = "HMAC " + getAuthorizationPrefix() + user
				+ ":" + getHmacSign(params, currentTime);
		post.addHeader(AbstractHttpRequest.HEADER_AUTHORIZATION,
				authorizationValue);
		post.addHeader("Shareppy-Timestamp", String.valueOf(currentTime));
	}

	private String getHmacSign(HttpRequestParams params, long currentTime) {
		String clearText = getClearText(params, currentTime);
		String base64 = CryptoUtil.hmac_sha512(hmac, clearText.toString());
		if (base64 != null) {
			base64 = base64.replace("\n", "").replace("\r", "");
		}
		return base64;
	}

	private String getClearText(HttpRequestParams params, long currentTime) {
		StringBuilder clearText = new StringBuilder("POST\n");
		clearText.append(service).append("\n");
		clearText.append(AbstractHttpRequest.HEADER_SHAREPPY_TIMESTAMP)
				.append(":").append(currentTime).append("\n");
		clearText.append(AbstractHttpRequest.HEADER_USER_AGENT).append(":")
				.append(getUserAgent()).append("\n");
		clearText.append(AbstractHttpRequest.HEADER_CONTENT_TYPE).append(":")
				.append(getContentType()).append("\n");
		clearText.append(params.toString());
		return clearText.toString();
	}

	protected String getAuthorizationPrefix() {
		return "id:";
	}
}